<template>
  <a-card :bordered="false" title="">
    <a-spin :spinning="myLoading">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="单位名称">
                <a-input v-model="queryParam.deptname" placeholder="请输入单位名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
               <a-form-item label="专业名称">
                    <!-- <a-input v-model="queryParam.majorname" placeholder="请输入专业名称" /> -->
                    <a-select v-model="queryParam.majorcode" placeholder="请选择" default-value="0" >
                      <a-select-option  v-for="(obj, index) in selectData['001']" :key="index" :value="obj.code">{{obj.name}}</a-select-option>
                    </a-select>
                  </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-item label="对象">
                    <a-select  v-model="queryParam.object" >
                      <a-select-option value="青年学生"> 青年学生 </a-select-option>
                      <a-select-option value="士兵学员"> 士兵学员 </a-select-option>
                    </a-select>
                  </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-item label="艰苦地区">
                <a-select  v-model="queryParam.hardFlg" >
                  <a-select-option value="是"> 是 </a-select-option>
                  <a-select-option value="否"> 否 </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="() => {this.clearRowSelection();getData()}">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => {this.clearRowSelection();queryParam = {};getData()}">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="table-page-search-wrapper">
        <div class="table-operator">
          <a-button type="primary" icon="plus" @click="add">添加单位</a-button>
          <a-popconfirm title="是否删除选中记录?" @confirm="allDel" @cancel="cancel" okText="是" cancelText="否" >
            <a-button type="primary" icon="del">选择删除</a-button>
          </a-popconfirm>
          <a-popconfirm title="是否删除所有记录?" @confirm="delAll" @cancel="cancel" okText="是" cancelText="否" >
            <a-button type="primary" icon="del">一键删除</a-button>
          </a-popconfirm>
          <a-button type="primary" icon="download" @click="downFile">模板下载</a-button>
          <a-upload :customRequest="downloadFilesCustomRequest" :fileList="[]">  
            <a-button type="primary" icon="upload">单位导入</a-button>
          </a-upload>
          
        </div>
        <a-table
          class="components-table-demo-nested"
          ref="table" 
          :columns="columns" 
          :row-key="record => record.companyId" 
          :data-source="data" 
          :pagination="pagination"
          :row-selection="rowSelection"
          :scroll="{ x: 'max-content' }"
          @change="handleTableChange">
          <span slot="action" slot-scope="text, record">
            <a @click="edit(record)">编辑</a>
            <a-divider type="vertical" />
            <!-- <a @click="edit(record)">预览</a>
                    <a-divider type="vertical" /> -->
            <a-popconfirm title="是否删除该条记录?" @confirm="del(record)" @cancel="cancel" okText="是" cancelText="否" >
              <a href="#">删除</a>
            </a-popconfirm>
          </span>
        </a-table>
      </div>
    </a-spin>
    <addCompany ref="modal" @ok="handleOk"></addCompany>
  </a-card>
</template>

<script>
  import addCompany from './modules/addCompany'
  import { getUrl,postAxiosUrl,uploadUrl } from '@/api/manage'
  import my from '@/api/my/my'
  export default {
    components: {
      addCompany
    },
    data() {
      return {
        defaultActiveKey : '',
        activeKey : '',
        columns: [
          {dataIndex:'deptname',title: '单位名称',},
          {dataIndex:'companyNum',title: '单位岗位数量',},
          {dataIndex:'trueNum',title: '单位岗位可选数量',},
          {dataIndex:'schoolname',title: '院校名称',},
          {dataIndex:'majorcode',title: '专业代码',},
          {dataIndex:'majorname',title: '专业名称',},
          {dataIndex:'target',title: '培养目标',},
          {dataIndex:'object',title: '对象',},
          {dataIndex:'schlength',title: '学制',},
          {dataIndex:'edu',title: '学历',},
          {dataIndex:'gender',title: '性别',},
          {dataIndex:'hardFlg',title: '是否艰苦地区',},
          {title: '操作',width : 130,fixed: 'right',scopedSlots: { customRender: 'action' }}
        ],
        data: [],
        pagination: {},
        myLoading: false,
        pagination: {size:'small'},
        queryParam:{},
        dataListSelectionList: [],
        selectedRowKeys: [],
        selectData:{}
      }
    },
    mounted() {
        this.getData()
         this.getSelectData()
    },
    computed: {
      rowSelection() {
        return {
          //onChange方法，rowSelection改变时触发
          onChange: (selectedRowKeys, list) => {
            //获取选中行的key元素，和下面selectedRowKeys属性配合使用，表示给rowSelection绑定一个v-model，为this.selectedRowKeys
            this.selectedRowKeys=selectedRowKeys
            //获取选中的行的所有元素
            this.dataListSelectionList = list
          },
          selectedRowKeys:this.selectedRowKeys,
        }
      },
    },
    methods: {
      getSelectData(params = {}) {
        var _this = this
        getUrl('cutDictionary/getAllSelect', params)
          .then(res => {
            console.log(res)
            _this.selectData = res.result
          })
      },
      clearRowSelection() {
        //将选中行的所有元素置空
        this.dataListSelectionList = []
        //将选中行的keys置空（即清空选中状态）
        this.selectedRowKeys=[]
      },
      allDel(){
        console.log('selectedRowKeys',this.selectedRowKeys)
        console.log('dataListSelectionList',this.dataListSelectionList)
        var _this = this
        _this.confirmLoading = true
        postAxiosUrl('graduationCompany/delAll', {dataListSelectionList:_this.dataListSelectionList,selectedRowKeys:_this.selectedRowKeys})
        .then(res => {
          if(res.success){
            _this.confirmLoading = false
            _this.$message.info('删除成功')
            this.clearRowSelection()
            _this.getData()
          }
        })
      },
      delAll(){
        var _this = this
        _this.confirmLoading = true
        postAxiosUrl('graduationCompany/delAllData', {})
        .then(res => {
          if(res.success){
            _this.confirmLoading = false
            _this.$message.info('删除成功')
            this.clearRowSelection()
            _this.getData()
          }
        })
      },
      dateFilter(value){
        var date = new Date(value)
        var year = date.getFullYear() + '年'
          var month = date.getMonth()+1 + '月'
          var day = date.getDate() + '日 '
          var hour = (date.getHours() < 10 ?('0' + date.getHours()) : date.getHours())+ ':'
          var min = (date.getMinutes() < 10 ?('0' + date.getMinutes()) : date.getMinutes())+ ':'
          var sec = (date.getSeconds() < 10 ?('0' + date.getSeconds()) : date.getSeconds())
        var formatDate = year + month + day + hour +min +sec
        return formatDate
      },
      downFile () {
        const a = document.createElement('a')
        a.href = my.baseURL + `graduationCompany/downloadExcel` // 这里的请求方式为get，如果需要认证，接口上需要带上token
        a.click()
      },
       // 重写a-upload的文件上传处理方式
      downloadFilesCustomRequest (data) {  
          this.confirmLoading = true
          this.saveFile(data)  
      },  
      // 上传并保存文件
      saveFile (data){  
        var _this = this
        const formData = new FormData()  
        formData.append('file', data.file)  
        uploadUrl('graduationCompany/upload',formData).then((res) => {
          console.log(res)
          if (res.data.success){
            _this.confirmLoading = false
             _this.$message.info(res.data.result)
             _this.queryParam = {}
            _this.getData()
          }else{
            _this.confirmLoading = false
            _this.$message.error(res.data.error)
          }
        })
      },
      handleOk(){
          this.getData()
      },
      add(){
        this.$refs.modal.add()
      },
      edit(record) {
        this.$refs.modal.edit(record)
      },
      del(record) {
        var _this = this
        _this.confirmLoading = true
        postAxiosUrl('graduationCompany/del', record)
        .then(res => {
          if(res.success){
            _this.confirmLoading = false
            _this.$message.info('删除成功')
            _this.getData()
          }
        })
      },
      handleTableChange(pagination, filters, sorter) {
        console.log(pagination)
        const pager = { ...this.pagination
        }
        pager.current = pagination.current
        this.pagination = pager
        // this.clearRowSelection()
        this.getData({
          results: pagination.pageSize,
          page: pagination.current,
          sortField: sorter.field,
          sortOrder: sorter.order,
          ...filters,
        })
      },
      getData(params = {}) {
          var _this = this
          _this.myLoading = true
          params['stuname'] = _this.queryParam.stuname
          params['majorcode'] = _this.queryParam.majorcode
          params['object'] = _this.queryParam.object
          params['hardFlg'] = _this.queryParam.hardFlg
          getUrl('graduationCompany/getAllList', params)
            .then(res => {
               _this.myLoading = false
              _this.data = res.result.data
              
              const pagination = { ...this.pagination }
              // Read total count from server
              pagination.total = res.result.totalCount
              pagination.showTotal = total => `共 ${total} 条`
              pagination.showQuickJumper = true
              this.pagination = pagination

            })
        
      },
      cancel(e) {
      },
      subCallback(key) {
        this.activeKey = key
        this.getData(key)
      }
    }
  }
</script>
<style>

</style>